package org.hanbo.code.repository.action;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.hanbo.code.repository.exception.CodeSnippetActionNotAuthorizedException;
import org.hanbo.code.repository.exception.CodeSnippetNotFoundException;
import org.hanbo.code.repository.exception.ErrorDescription;
import org.hanbo.code.repository.persistence.entity.CodeSnippet;
import org.hanbo.code.repository.persistence.entity.CodeSnippetDAO;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class RetrieveCodeSnippetByIdAction extends CodeSnippetActionBase implements ServletRequestAware
{
	private static final long serialVersionUID = -4040463002300891505L;
	
	private HttpServletRequest servletReq;
	private ErrorDescription errorDescription;

	private String authorEmailField;
	private String additionalLinks = "";
	
	public void setServletRequest(HttpServletRequest arg0)
	{
		servletReq = arg0;
	}
	
	public String getAuthorEmailField()
	{
		return authorEmailField;
	}
	
	public String execute()
	{
		if (!checkLogin())
		{
			return super.getCurrentStageValue();
		}
		
		if (!super.checkRegistration())
		{
			return super.getCurrentStageValue();
		}
		
		String loggedInUserEmail = super.getRegisteredUser().getUserEmail().getEmail();

		try
		{
			if(servletReq != null)
			{
				String requestType = servletReq.getParameter("type");
				String retrievalId = servletReq.getParameter("id");
				
				if (StringUtils.isEmpty(requestType) || StringUtils.isEmpty(retrievalId))
				{
					throw new IllegalArgumentException(
						"Request does not contain \"type\" or \"id\" for searching code snippet"
					);
				}
				
				long actualId = -1;
				try
				{
					actualId = Long.parseLong(retrievalId);
				}
				catch(NumberFormatException e)
				{
					throw e;
				}
				
				Key codeSnippetId = KeyFactory.createKey(requestType, actualId);
				CodeSnippetDAO codeSnippetRetriever = new CodeSnippetDAO();
				try
				{
					codeSnippetRetriever.acquirePersistenceManager();
					CodeSnippet snippet = codeSnippetRetriever.getCodeSnippetById(codeSnippetId);
					if (snippet == null)
					{
						throw new CodeSnippetNotFoundException(actualId);
					}
					
					this.authorEmailField = snippet.getAuthorEmail();
					if (this.authorEmailField.equals(loggedInUserEmail))
					{
						long codeSnippetIdUsed = codeSnippetId.getId();
						additionalLinks = " | <a href='DeleteCodeSnippetById.action?type=CodeSnippet&id="
							+ codeSnippetIdUsed
							+ "'>Delete Snippet</a> | <a href='PreUpdateCodeSnippet.action?type=CodeSnippet&id="
							+ codeSnippetIdUsed + "'>Update Snippet</a>";
					}
					else
					{
						if (!snippet.isAvailableTpPublic())
						{
							throw new CodeSnippetActionNotAuthorizedException(
								"Viewing code snippet that is not available to public."
							);
						}
					}
					this.convertCodeSnippetToThis(snippet);
				}
				catch (Exception e)
				{
					throw e;
				}
				finally
				{
					codeSnippetRetriever.releasePersistenceManager();
				}
			}
		}
		catch(CodeSnippetNotFoundException e)
		{
			errorDescription = new ErrorDescription(e);
			return ERROR;
		}
		catch(Exception e)
		{
			errorDescription = new ErrorDescription(1000, e);
			return ERROR;
		}
			
		return SUCCESS;
	}
	
	public String getUserName()
	{
		return super.getLoggedInUser().getNickname();
	}
	
	public String getAdditionalLinks()
	{
		return additionalLinks;
	}
		
	public String getLogoutUrl()
	{
		return super.createLogOutLink("../index.action");
	}
	
	public String getRedirectLogin()
	{
		return super.createLogInLink("../index.action");
	}

	public ErrorDescription getErrorDescription()
	{
		return errorDescription;
	}
}
